package com.xjc.agent.core;

import com.xjc.agent.core.intercept.EnhanceListener;
import com.xjc.agent.core.intercept.MonitorMethod;
import com.xjc.agent.core.util.AgentUtil;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.File;
import java.lang.instrument.Instrumentation;

/**
 * @author: 谢君臣
 * @Date: 2023/1/1-16:52
 * @version: 1.0
 * @function:
 */

public class AgentBootstrap {

    public void main(String args, Instrumentation inst) {
        System.out.println("==========start preMain========");
        String agentPath = AgentUtil.findAgentJarPath();
        String libPath = File.separator + "lib";
        String confPath = File.separator + "conf";
        String pluginPath = File.separator + "plugin";
        ClassLoader rootClassLoader = ClassLoader.getSystemClassLoader().getParent();
//        AgentClassLoader agentClassLoader = new AgentClassLoader(agentPath, libPath, confPath, rootClassLoader);
//        Class<?> aClass = agentClassLoader.loadClass("com.xjc.agent.core.intercept.MonitorMethod");

        AgentBuilder.Ignored agentBuilder =new  AgentBuilder.Default()
                .ignore(
                        ElementMatchers.nameStartsWith("java.utils.")
                        .or(ElementMatchers.nameStartsWith("java.lang."))
                        .or(ElementMatchers.named("toString"))
                );

        AgentBuilder.Transformer transformer = (
                builder,
                typeDescription,
                classLoader,
                javaModule,
                domain
        ) -> builder
                .method(ElementMatchers.any() // 拦截所有
                        .and(ElementMatchers.not(ElementMatchers.isConstructor())) // 过滤构造器
                        .and(ElementMatchers.not(ElementMatchers.isSetter().or(ElementMatchers.isGetter())))// setter getter方法
                ).intercept(MethodDelegation.to(MonitorMethod.class));

        agentBuilder.type(ElementMatchers.nameStartsWith("com.xjc.demo.controller"))
                .transform(transformer)
                .with(new EnhanceListener())
                .installOn(inst);
    }
}
